<?php
/**
 * iWebkit for MyBB, provide a mobile friendly interface.
 * Copyright (C) 2010  Christopher John Jackson
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
*/

class commandAndFunction {
    private $data;
    private $forumpermissions;
    private $fcache;

    public function  __construct() {
        $this->data['topbar'] = " ";
        $this->data['content'] = " ";
    }

    public function getData() {
        return $this->data;
    }

    public function _default() {
        global $db;
        // Fetch all of the forum permissions
        $this->forumpermissions = forum_permissions();

        // Fetch forums
        $query = $db->simple_select("forums", "*", "active != '0' AND password=''", array('order_by' => 'pid, disporder'));
        while($forum = $db->fetch_array($query)) {
            $this->fcache[$forum['pid']][$forum['disporder']][$forum['fid']] = $forum;
        }

        // Build our forum listing
        $forums = $this->getforums();
        //$postdata .= "<div class=\"forumlist\"><ul>".$forums."</ul></div>";
        $this->data['content'].= $forums;
    }

    public function command_signin() {
        global $mybb;
        $this->data['content'] =  "<form method=\"post\" action=\"".$mybb->settings['bburl']."/member.php\">";
        $this->data['content'] .= "<ul class=\"pageitem\">
							<li class=\"bigfield\"><input name=\"username\" placeholder=\"Username\" type=\"text\" /></li>
							<li class=\"bigfield\"><input name=\"password\" placeholder=\"Password\" type=\"password\" /></li>
											<li class=\"button\"><input name=\"submit\" type=\"submit\" value=\"Sign In\" /></li>
											<input type=\"hidden\" name=\"action\" value=\"do_login\">
											<input type=\"hidden\" name=\"url\" value=\"".$mybb->settings['bburl']."/iphone\">
						</ul>";
        $this->data['content'] .= "</form>";
    }

    public function command_signout() {
        global $plugins, $mybb, $db;
        $plugins->run_hooks("member_logout_start");
        my_unsetcookie("mybbuser");
        my_unsetcookie("sid");
        if($mybb->user['uid']) {
            $time = TIME_NOW;
            $lastvisit = array(
                    "lastactive" => $time-900,
                    "lastvisit" => $time,
            );
            $db->update_query("users", $lastvisit, "uid='".$mybb->user['uid']."'");
            $db->delete_query("sessions", "sid='".$session->sid."'");
        }
        $plugins->run_hooks("member_logout_end");
        $this->data['content'] = "<ul class=\"pageitem\"><li class=\"textbox\">\n
				<span class=\"header\">Forum Message</span>\n
				<p>You've been logged out.</p>\n
				</li></ul>";
        $this->data['content'] .= "<ul class=\"pageitem\"><li class=\"menu\">\n
									<a href=\"".$mybb->settings['bburl']."/iphone\"><span class=\"name\">".$mybb->settings['bbname']."</span><span class=\"arrow\"></span></a></li></ul>";
    }

    public function command_forum() {
        global $mybb, $db, $parser, $forum, $id, $archiveurl;
        $this->data['topbar'] = "<div id=\"leftnav\">
	<a href=\"".$mybb->settings['bburl']."/iphone\"><img alt=\"home\" src=\"".$mybb->settings['bburl']."/iphone/images/home.png\"</a>
            <a href=\"javascript: history.go(-1)\">Back</a>
	</div>";

        // Check if we have permission to view this forum
        $this->forumpermissions = forum_permissions($forum['fid']);
        if($this->forumpermissions['canview'] != 1) {
            $this->data['content'] = "<ul class=\"pageitem\"><li class=\"textbox\">\n
					<span class=\"header\">Forum Error</span>\n
					<p>Sorry, but you do not have access to this forum.</p>\n
					</li></ul>";
            return null;
        }
        $canpostthreads = $this->forumpermissions['canpostthreads'];

        // Paginate this forum
        $query = $db->simple_select("threads", "COUNT(tid) AS threads", "fid='$id' AND visible='1'");
        $threadcount = $db->fetch_field($query, 'threads');

        if($threadcount < 1) {
            $this->data['content'] = "<ul class=\"pageitem\"><li class=\"textbox\">\n
					<span class=\"header\">Forum Message</span>\n
					<p>There are currently no threads in this forum.</p>\n
					</li></ul>";

            if($canpostthreads == 1) {
                $this->data['content'] .= "<ul class=\"pageitem\">";
                $this->data['content'] .= "<li class=\"menu\"><a href=\"".$archiveurl."/index.php/newthread-".$id.".html\"><span class=\"name\">Post New Thread</span></a></li>";
                $this->data['content'] .= "</ul>";
            }
            return null;
        }

        $pagenumber = null;
        $threadperpage = 20;
        if(!isset($_GET['page']) || !is_numeric($_GET['page'])) {
            $pagenumber = 1;
        } else {
            $pagenumber = (int)$_GET['page'];
        }

        $lastpage = ceil($threadcount/$threadperpage);

        if($pagenumber < 1) {
            $pagenumber = 1;
        } elseif($pagenumber > $lastpage) {
            $pagenumber = $lastpage;
        }

        $forumquery = $db->simple_select("forums", "name", "fid='".$forum['fid']."'", array('limit' => 1));
        $forumname = $db->fetch_field($forumquery, 'name');

        if($pagenumber == 1) {
            $this->data['content'] .= $this->getsubforums($forum['fid'], $forumname);
        }

        $this->data['content'] .= "<span class=\"graytitle\">".htmlspecialchars($forumname)."</span>";
        $this->data['content'] .= "<ul class=\"pageitem\">";

        // Start fetching the threads
        $query = $db->simple_select("threads", "*", "fid='$id' AND visible='1'", array('order_by' => 'sticky DESC, lastpost DESC','limit' => ($pagenumber-1)*$threadperpage.','.$threadperpage));
        while($thread = $db->fetch_array($query)) {
            $thread['subject'] = htmlspecialchars_uni($parser->parse_badwords($thread['subject'], array('strip_tags' => 'yes')));
            $prefix = "";
            if($thread['sticky'] == 1) {
                $prefix = " ! ";
            }

            if($thread['replies'] != 1) {
                $lang_reply_text = $lang->archive_replies;
            }
            else {
                $lang_reply_text = $lang->archive_reply;
            }
            $thread['date'] = my_date($mybb->settings['dateformat'].", ".$mybb->settings['timeformat'], $thread['dateline'], "", 0);
            $this->data['content'] .= "<li class=\"menu\"><a href=\"".$archiveurl."/index.php/thread-".$thread['tid'].".html\"> <span class=\"name\">".
                    $prefix."".strtrim($thread['subject'], 20)."</span><span class=\"comment\">".$thread['replies']." ".$lang_reply_text.
                    "</span><span class=\"arrow\"></span></a></li><li class=\"textbox\" style=\"font-size: 0.75em;\"><span style=\"float: right;\">".
                    $thread['date']."</span>^ ".$thread['username']."</li>";
        }

        $this->data['content'] .= "</ul>";
        if(!($pagenumber == 1 && $pagenumber == $lastpage) || $canpostthreads == 1) {
            $this->data['content'] .= "<ul class=\"pageitem\">";
            if($pagenumber != 1) {
                $previous = $pagenumber-1;
                $this->data['content'] .= "<li class=\"menu\"><a href=\"".$_SERVER['PHP_SELF']."?page=".$previous."\"><span class=\"name\">Previous Page</span></a></li>";
            }
            if($pagenumber != $lastpage) {
                $next = $pagenumber+1;
                $this->data['content'] .= "<li class=\"menu\"><a href=\"".$_SERVER['PHP_SELF']."?page=".$next."\"><span class=\"name\">Next Page</span></a></li>";
            }
            if($canpostthreads == 1) {
                //".$archiveurl."/index.php/newthread-".$id.".html
                $this->data['content'] .= "<li class=\"menu\"><a href=\"".$archiveurl."/index.php/newthread-".$id.".html\"><span class=\"name\">Post New Thread</span></a></li>";
            }
            $this->data['content'] .= "</ul>";
        }
    }

    public function command_thread() {
        global $mybb, $db, $parser, $forum, $id, $archiveurl, $thread;
        $this->data['topbar'] = "<div id=\"leftnav\">
	<a href=\"".$mybb->settings['bburl']."/iphone\"><img alt=\"home\" src=\"".$mybb->settings['bburl']."/iphone/images/home.png\"</a>
            <a href=\"javascript: history.go(-1)\">Back</a>
	</div>";

        $thread['subject'] = htmlspecialchars_uni($parser->parse_badwords($thread['subject'], array('strip_tags' => 1)));
        $this->data['content'] .= "<span class=\"graytitle\">".$thread['subject']."</span>";

        // Fetch the forum this thread is in
        $query = $db->simple_select("forums", "*", "fid='".$thread['fid']."' AND active!='0' AND type='f' AND password=''");
        $forum = $db->fetch_array($query);
        if(!$forum['fid']) {
            $this->data['content'] = "<ul class=\"pageitem\"><li class=\"textbox\">\n
					<span class=\"header\">Forum Error</span>\n
					<p>Sorry, but you do not have access to this forum.</p>\n
					</li></ul>";
            return null;
        }

        // Check if we have permission to view this thread
        $this->forumpermissions = forum_permissions($forum['fid']);
        if($this->forumpermissions['canview'] != 1) {
            $this->data['content'] = "<ul class=\"pageitem\"><li class=\"textbox\">\n
					<span class=\"header\">Forum Error</span>\n
					<p>Sorry, but you do not permission to access this thread.</p>\n
					</li></ul>";
            return null;
        }
        $canpostreplys = $this->forumpermissions['canpostreplys'];
        //print_r($this->forumpermissions);
        //Count the post
        $query = $db->query("
			SELECT COUNT(*) as count
			FROM ".TABLE_PREFIX."posts p
			LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid=p.uid)
			WHERE p.tid='$id' AND visible='1'
			ORDER BY p.dateline
                ");
        $postcount = (int)$db->fetch_field($query,'count');

        $pagenumber = null;
        $msgperpage = 10;
        if(!isset($_GET['page']) || !is_numeric($_GET['page'])) {
            $pagenumber = 1;
        } else {
            $pagenumber = (int)$_GET['page'];
        }

        $lastpage = ceil($postcount/$msgperpage);

        if($pagenumber < 1) {
            $pagenumber = 1;
        } elseif($pagenumber > $lastpage) {
            $pagenumber = $lastpage;
        }

        //($pagenumber-1)*$msgperpage.','.$msgperpage

        // Start fetching the posts
        $query = $db->query("
			SELECT u.*, u.username AS userusername, p.*
			FROM ".TABLE_PREFIX."posts p
			LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid=p.uid)
			WHERE p.tid='$id' AND visible='1'
			ORDER BY p.dateline
                        LIMIT ".($pagenumber-1)*$msgperpage.','.$msgperpage."
                ");
        $this->data['content'] .= "<ul class=\"pageitem\">";
        while($post = $db->fetch_array($query)) {
            $post['date'] = my_date($mybb->settings['dateformat'].", ".$mybb->settings['timeformat'], $post['dateline'], "", 0);
            // Parse the message
            if($post['smilieoff'] == 1) {
                $allowsmilies = 0;
            }
            else {
                $allowsmilies = $forum['allowsmilies'];
            }
            $settings = array(
                    'allow_html' => $forum['allowhtml'],
                    'allow_mycode' => $forum['allowmycode'],
                    'allow_smilies' => $allowsmilies,
                    'allow_imgcode' => $forum['allowimgcode'],
                    'nl2br' => 1,
                    'filter_badwords' => 1
            );
            $post['message'] = $parser->parse_message($post['message'], $settings);
            //$replace = array("\r", "\n", "\r\n", "\n\r", "<br>", "<br />");
            //$post['message'] = str_replace($replace, "<br />", $post['message']);
            //$post['message'] = str_replace("images/smilies", $mybb->settings['bburl']."/images/smilies", $post['message']);

            // do me code
            if($forum['allowmycode'] != 0) {
                $post['message'] = $parser->parse_mycode($post['message'], array('me_username' => $post['userusername']));
            }

            $icon = "";
            if($post['icon'] != 0) {
                $iconnumber  = $post['icon'];
                $iconquery = $db->simple_select("icons", "path", "iid='".$iconnumber."'");
                $iconpath = "/".$db->fetch_field($iconquery, 'path');
                $icon = "<img src=\"".$mybb->settings['bburl'].$iconpath."\" /> ";
            }

            $reply = "";
            if($canpostreplys == 1) {
                $reply = "<a href=\"".$archiveurl."/index.php/newreply-".$id.".html?replyto=".$post['pid']."\"><span class=\"name\">Reply</span></a>";
            }

            // Finally show the post
            $this->data['content'] .= "<li class=\"textbox\"><span style=\"float: right; font-size: 0.75em;\">".$post['date']."</span><span class=\"header\">".$icon.$post['userusername']."</span>";
            $this->data['content'] .= $post['message']."<br /><span style=\"float: right; font-size: 0.75em;\">$reply</span></li>";
            //$postdata .= "<font style=\"font-size: 14px\">Posted on ".$post['date']."</font></li></ul>";
        }
        $this->data['content'] .= "</ul>";
        if(!($pagenumber == 1 && $pagenumber == $lastpage) || $canpostreplys == 1) {
            $this->data['content'] .= "<ul class=\"pageitem\">";
            if($pagenumber != 1) {
                $previous = $pagenumber-1;
                $this->data['content'] .= "<li class=\"menu\"><a href=\"".$_SERVER['PHP_SELF']."?page=".$previous."\"><span class=\"name\">Previous Page</span></a></li>";
            }
            if ($pagenumber != $lastpage) {
                $next = $pagenumber+1;
                $this->data['content'] .= "<li class=\"menu\"><a href=\"".$_SERVER['PHP_SELF']."?page=".$next."\"><span class=\"name\">Next Page</span></a></li>";
            }
            if($canpostreplys == 1) {
                if($thread['closed'] == 1) {
                    $this->data['content'] .= "<li class=\"menu\"><a href=\"".$archiveurl."/index.php/newreply-".$id.".html\"><span class=\"name\">Closed</span></a></li>";
                } else {
                    $this->data['content'] .= "<li class=\"menu\"><a href=\"".$archiveurl."/index.php/newreply-".$id.".html\"><span class=\"name\">Post New Reply</span></a></li>";
                }
            }
            if(is_moderator($thread['fid'], "canopenclosethreads")) {
                if($thread['closed'] == 1) {
                    $this->data['content'] .= "<li class=\"menu\"><a href=\"".$archiveurl."/index.php/lockthread-".$id.".html\"><span class=\"name\">Open This Thread</span></a></li>";
                } else {
                    $this->data['content'] .= "<li class=\"menu\"><a href=\"".$archiveurl."/index.php/lockthread-".$id.".html\"><span class=\"name\">Close This Thread</span></a></li>";
                }
            }
            $this->data['content'] .= "</ul>";
        }
    }

    public function command_newthread() {
        global $id, $mybb, $archiveurl, $db;
        $this->data['topbar'] = "<div id=\"leftnav\">
	<a href=\"".$mybb->settings['bburl']."/iphone\"><img alt=\"home\" src=\"".$mybb->settings['bburl']."/iphone/images/home.png\"</a>
            <a href=\"javascript: history.go(-1)\">Back</a>
	</div>";

        if($mybb->user['uid'] == 0 || $id == 0) {
            $this->_default();
            return null;
        }

        $this->forumpermissions = forum_permissions($id);
        if($this->forumpermissions['canpostthreads'] != 1) {
            $this->data['content'] = "<ul class=\"pageitem\"><li class=\"textbox\">\n
					<span class=\"header\">Forum Error</span>\n
					<p>Sorry, but you do not have permission to post new threads in this forum.</p>\n
					</li></ul>";
            return null;
        }

        $query = $db->simple_select("forums", "COUNT(*) AS forums", "fid='$id' AND type='f' AND active='1' AND open='1'");
        $forumscount = $db->fetch_field($query, 'forums');

        if($forumscount == 0) {
            $this->data['content'] = "<ul class=\"pageitem\"><li class=\"textbox\">\n
					<span class=\"header\">Forum Error</span>\n
					<p>Forum either does not exist, is category, is not active or not open.</p>\n
					</li></ul>";
            return null;
        }

        $signature == "";
        if($mybb->user['signature'] != '' || $_POST['signature'] == 1) {
            $signature = ' checked="checked"';
        }

        $lockoption = "";
        if(is_moderator($id, "canopenclosethreads")) {
            $lockoptionchecked = '';
            if($_POST['closethread'] == 1) {
                $lockoptionchecked = ' checked="checked"';
            }

            $lockoption = '<li class="checkbox"><span class="name">Close Thread</span><input name="closethread" type="checkbox" value="1" '.$lockoptionchecked.' />'."\n";
        }

        $this->data['content'] .= "<form action=\"".$archiveurl."/index.php/submitnewthread-".$id.".html\" method=\"post\"><fieldset>\n".
                '<span class="graytitle">Post New Thread</span><ul class="pageitem">'."\n".
                '<li class="bigfield"><input name="subject" placeholder="Subject" type="text" value="'.$_POST['subject'].'" /></li></ul>'."\n".
                '<span class="graytitle">Message</span><ul class="pageitem"><li class="textbox">'."\n".
                '<textarea name="message" rows="4">'.$_POST['message'].'</textarea></li>'."\n".
                '<li class="checkbox"><span class="name">Signature</span><input name="signature" type="checkbox" value="1" '.$signature.' />'."\n".
                $lockoption.
                '<li class="button"><input name="submit" type="submit" value="Submit"/></li></ul>';

        //".$archiveurl."/index.php/submitnewthreadthread-".$id.".html
    }

    public function command_submitnewthread() {
        global $id, $mybb, $archiveurl, $db;


        if($mybb->user['uid'] == 0 || $id == 0) {
            $this->_default();
            return null;
        }

        $this->forumpermissions = forum_permissions($id);
        if($this->forumpermissions['canpostthreads'] != 1) {
            $this->data['content'] = "<ul class=\"pageitem\"><li class=\"textbox\">\n
					<span class=\"header\">Forum Error</span>\n
					<p>Sorry, but you do not have permission to post new threads in this forum.</p>\n
					</li></ul>";
            return null;
        }

        $query = $db->simple_select("forums", "COUNT(*) AS forums", "fid='$id' AND type='f' AND active='1' AND open='1'");
        $forumscount = $db->fetch_field($query, 'forums');

        if($forumscount == 0) {
            $this->data['content'] = "<ul class=\"pageitem\"><li class=\"textbox\">\n
					<span class=\"header\">Forum Error</span>\n
					<p>Forum either does not exist, is category, is not active or not open.</p>\n
					</li></ul>";
            return null;
        }

        //Set up posthandler
        require_once MYBB_ROOT."inc/datahandlers/post.php";
        $posthandler = new PostDataHandler("insert");
        $posthandler->action = "thread";

        //Set the thread data that came from the input to the $thread array.
        $new_thread = array(
                "fid" => $id,
                "subject" => $_POST['subject'],
                "icon" => -1,
                "uid" => $mybb->user['uid'],
                "username" => $mybb->user['username'],
                "message" => $_POST['message'],
                "ipaddress" => get_ip(),
                "posthash" => md5($mybb->user['uid'].random_str()),
                "savedraft" => 0
        );
        $new_thread['options']['signature'] = $_POST['signature'];

        if(is_moderator($id, "canopenclosethreads")) {
            if($_POST['closethread'] == 1) {
                $new_thread['modoptions']['closethread'] = (int)$_POST['closethread'];
            }
        }

        $posthandler->set_data($new_thread);

        $valid_thread = $posthandler->validate_thread();

        $error = array();
        if(!$valid_thread) {
            $error = $posthandler->get_friendly_errors();
        }

        if(count($error) > 0) {
            $this->data['content'] = '<ul class="pageitem"><li class="textbox">'.inline_error($error).'</li></ul>';
            $this->command_newthread();
            $this->data['topbar'] = "";
            return null;
        }

        $thread_info = $posthandler->insert_thread();
        $tid = $thread_info['tid'];
        $visible = $thread_info['visible'];

        $message = "";
        $url = "";
        if(!$visible) {
            $message = "New Thread is under moderation queue";
            $url = "<li class=\"menu\"><a href=\"".$archiveurl."\"><span class=\"name\">Go to home page</span></a></li>";
        } else {
            $message = "New Thread has been posted";
            $url = "<li class=\"menu\"><a href=\"".$archiveurl."/index.php/thread-".$tid."\"><span class=\"name\">Go to new thread</span></a></li>";
        }
        $this->data['content'] = '<ul class="pageitem"><li class="textbox">'.$message.'</li>'.$url.'</ul>';
    }

    public function command_newreply() {
        global $id, $mybb, $archiveurl, $db;
        $this->data['topbar'] = "<div id=\"leftnav\">
	<a href=\"".$mybb->settings['bburl']."/iphone\"><img alt=\"home\" src=\"".$mybb->settings['bburl']."/iphone/images/home.png\"</a>
            <a href=\"javascript: history.go(-1)\">Back</a>
	</div>";

        if($mybb->user['uid'] == 0 || $id == 0) {
            $this->_default();
            return null;
        }

        $query = $db->query("SELECT * FROM ".TABLE_PREFIX."threads WHERE tid='$id' AND visible='1' AND poll='0' AND closed NOT LIKE 'moved|%'");
        $thread = $db->fetch_array($query);

        $this->forumpermissions = forum_permissions($thread['fid']);
        //print_r($this->forumpermissions);
        if($this->forumpermissions['canpostreplys'] != 1) {
            $this->data['content'] = "<ul class=\"pageitem\"><li class=\"textbox\">\n
					<span class=\"header\">Forum Error</span>\n
					<p>Sorry, but you do not have permission to post new replys in this forum.</p>\n
					</li></ul>";
            return null;
        }

        if(!is_moderator($id, "canopenclosethreads") && $thread['closed'] == 1) {
            $this->data['content'] = "<ul class=\"pageitem\"><li class=\"textbox\">\n
					<span class=\"header\">Forum Error</span>\n
					<p>Sorry, but you do not have permission to post new replys in closed thread.</p>\n
					</li></ul>";
            return null;
        }

        $query = $db->simple_select("forums", "COUNT(*) AS forums", "fid='".$thread['fid']."' AND type='f' AND active='1' AND open='1'");
        $forumscount = $db->fetch_field($query, 'forums');

        if($forumscount == 0) {
            $this->data['content'] = "<ul class=\"pageitem\"><li class=\"textbox\">\n
					<span class=\"header\">Forum Error</span>\n
					<p>Forum either does not exist, is category, is not active or not open.</p>\n
					</li></ul>";
            return null;
        }

        $subjectData = "";
        if(isset($_POST['subject'])) {
            $subjectData = $_POST['subject'];
        } else {
            $subjectData = "RE: ".$thread['subject'];
        }

        $isgnature = '';
        if($mybb->user['signature'] != '' || $_POST['signature'] == 1) {
            $signature = ' checked="checked"';
        }

        $replyto = '';
        $quote = '';
        if($_POST['replyto'] != '') {
            $replyto = $_POST['replyto'];
        } elseif($_GET['replyto'] != '') {
            $replyto = (int)$_GET['replyto'];
            //echo $replyto;
            $replytoquery = $db->simple_select("posts", "*", "pid='".$replyto."'");
            $replytoarray = $db->fetch_array($replytoquery);
            if(count($replytoarray) > 0 && $id == $replytoarray['tid']) {
                $message = $replytoarray['message'];
                $username = $replytoarray['username'];
                $dateline = $replytoarray['dateline'];
                $quote = "[quote='$username' pid='$replyto' dateline='$dateline']".$message."[/quote]\n\n";
            }
        }

        $lockoption = "";
        if(is_moderator($thread['fid'], "canopenclosethreads")) {
            $lockoptionchecked = '';
            if($_POST['closethread'] == 1 || $thread['closed']) {
                $lockoptionchecked = ' checked="checked"';
            }

            $lockoption = '<li class="checkbox"><span class="name">Close Thread</span><input name="closethread" type="checkbox" value="1" '.$lockoptionchecked.' />'."\n";
        }

        $this->data['content'] .= "<form action=\"".$archiveurl."/index.php/submitnewreply-".$id.".html\" method=\"post\"><fieldset>\n".
                '<span class="graytitle">Post New Reply</span><ul class="pageitem">'."\n".
                '<li class="bigfield"><input name="subject" placeholder="Subject" type="text" value="'.$subjectData.'" /></li></ul>'."\n".
                '<span class="graytitle">Message</span><ul class="pageitem"><li class="textbox">'."\n".
                '<textarea name="message" rows="4">'.$quote.$_POST['message'].'</textarea></li>'."\n".
                '<li class="checkbox"><span class="name">Signature</span><input name="signature" type="checkbox" value="1" '.$signature.' />'."\n".
                $lockoption.
                '<input name="replyto" type="hidden" value="'.$replyto.'" />'."\n".
                '<li class="button"><input name="submit" type="submit" value="Submit"/></li></ul>';
    }

    public function command_submitnewreply() {
        global $id, $mybb, $archiveurl, $db;

        if($mybb->user['uid'] == 0 || $id == 0) {
            $this->_default();
            return null;
        }

        $query = $db->query("SELECT * FROM ".TABLE_PREFIX."threads WHERE tid='$id' AND visible='1' AND poll='0' AND closed NOT LIKE 'moved|%'");
        $thread = $db->fetch_array($query);

        $this->forumpermissions = forum_permissions($thread['fid']);
        //print_r($this->forumpermissions);
        if($this->forumpermissions['canpostreplys'] != 1) {
            $this->data['content'] = "<ul class=\"pageitem\"><li class=\"textbox\">\n
					<span class=\"header\">Forum Error</span>\n
					<p>Sorry, but you do not have permission to post new replys in this forum.</p>\n
					</li></ul>";
            return null;
        }

        if(!is_moderator($id, "canopenclosethreads") && $thread['closed'] == 1) {
            $this->data['content'] = "<ul class=\"pageitem\"><li class=\"textbox\">\n
					<span class=\"header\">Forum Error</span>\n
					<p>Sorry, but you do not have permission to post new replys in closed thread.</p>\n
					</li></ul>";
            return null;
        }

        $query = $db->simple_select("forums", "COUNT(*) AS forums", "fid='".$thread['fid']."' AND type='f' AND active='1' AND open='1'");
        $forumscount = $db->fetch_field($query, 'forums');

        if($forumscount == 0) {
            $this->data['content'] = "<ul class=\"pageitem\"><li class=\"textbox\">\n
					<span class=\"header\">Forum Error</span>\n
					<p>Forum either does not exist, is category, is not active or not open.</p>\n
					</li></ul>";
            return null;
        }

        require_once MYBB_ROOT."inc/datahandlers/post.php";
        $posthandler = new PostDataHandler("insert");

        $post = array(
                "tid" => $id,
                "replyto" => $_POST['replyto'],
                "fid" => $thread['fid'],
                "subject" => $_POST['subject'],
                "icon" => -1,
                "uid" => $mybb->user['uid'],
                "username" => $mybb->user['username'],
                "message" => $_POST['message'],
                "ipaddress" => get_ip(),
                "posthash" => md5($mybb->user['uid'].random_str()),
                "savedraft" => 0
        );
        $post['options']['signature'] = $_POST['signature'];

        if(is_moderator($thread['fid'], "canopenclosethreads")) {
            if($_POST['closethread'] == 1) {
                $post['modoptions']['closethread'] = (int)$_POST['closethread'];
            } else {
                $post['modoptions']['closethread'] = 0;
            }
            if($thread['sticky'] == 1) {
                $post['modoptions']['stickthread'] = 1;
            }
        }

        $posthandler->set_data($post);

        $valid_post = $posthandler->validate_post();

        $error = array();
        if(!$valid_post) {
            $error = $posthanlder->get_friendly_errors();
        }

        if(count($error) > 0) {
            $this->data['content'] = '<ul class="pageitem"><li class="textbox">'.inline_error($error).'</li></ul>';
            $this->command_newreply();
            $this->data['topbar'] = "";
            return null;
        }

        $postinfo = $posthandler->insert_post();
        $pid = $postinfo['tid'];
        $visible = $postinfo['visible'];

        $message = "";
        $url = "";
        if($visible != 1) {
            $message = "New Reply is under moderation queue";
            $url = "<li class=\"menu\"><a href=\"".$archiveurl."\"><span class=\"name\">Go to home page</span></a></li>";
        } else {
            $message = "New Reply has been posted";
            $url = "<li class=\"menu\"><a href=\"".$archiveurl."/index.php/thread-".$id.".html\"><span class=\"name\">Go to new thread</span></a></li>";
        }
        $this->data['content'] = '<ul class="pageitem"><li class="textbox">'.$message.'</li>'.$url.'</ul>';
    }

    public function command_lockthread() {
        global $id, $mybb, $db, $archiveurl;

        if($mybb->user['uid'] == 0 || $id == 0) {
            $this->_default();
            return null;
        }

        $query = $db->query("SELECT * FROM ".TABLE_PREFIX."threads WHERE tid='$id' AND visible='1' AND poll='0' AND closed NOT LIKE 'moved|%'");
        $thread = $db->fetch_array($query);

        $this->forumpermissions = forum_permissions($thread['fid']);

        //print_r($this->forumpermissions);
        if(!is_moderator($thread['fid'], "canopenclosethreads")) {
            $this->data['content'] = "<ul class=\"pageitem\"><li class=\"textbox\">\n
					<span class=\"header\">Forum Error</span>\n
					<p>Sorry, but you do not have permission to (un)lock this thread.</p>\n
					</li></ul>";
            return null;
        }

        $state = "";
        if($thread['closed'] == 1) {
            $state = 'open';
        } else {
            $state = 'close';
        }

        $this->data['content'] .= "<span class=\"graytitle\">Are you sure you want to $state '".$thread['subject']."' thread?</span>";
        $this->data['content'] .= "<ul class=\"pageitem\">";
        $this->data['content'] .= "<li class=\"menu\"><a href=\"".$archiveurl."/index.php/lockthreadconfirmed-".$id.".html\"><span class=\"name\">Yes</span></a></li>";
        $this->data['content'] .= "<li class=\"menu\"><a href=\"".$archiveurl."/index.php/thread-".$id.".html\"><span class=\"name\">No</span></a></li>";
        $this->data['content'] .= "</ul>";
    }

    public function command_lockthreadconfirmed() {
        global $id, $mybb, $db, $archiveurl;

        if($mybb->user['uid'] == 0 || $id == 0) {
            $this->_default();
            return null;
        }

        $query = $db->query("SELECT * FROM ".TABLE_PREFIX."threads WHERE tid='$id' AND visible='1' AND poll='0' AND closed NOT LIKE 'moved|%'");
        $thread = $db->fetch_array($query);

        $this->forumpermissions = forum_permissions($thread['fid']);

        //print_r($this->forumpermissions);
        if(!is_moderator($thread['fid'], "canopenclosethreads")) {
            $this->data['content'] = "<ul class=\"pageitem\"><li class=\"textbox\">\n
					<span class=\"header\">Forum Error</span>\n
					<p>Sorry, but you do not have permission to (un)lock this thread.</p>\n
					</li></ul>";
            return null;
        }

        require_once MYBB_ROOT."inc/class_moderation.php";
        $moderation = new Moderation;

        if($thread['closed'] == 1) {
            $moderation->open_threads($id);
            $message = "'".$thread['subject']."' thread is now open.";
        } else {
            $moderation->close_threads($id);
            $message = "'".$thread['subject']."' thread is now close.";
        }
        $url = "<li class=\"menu\"><a href=\"".$archiveurl."/index.php/thread-".$id.".html\"><span class=\"name\">Go thread</span></a></li>";

        $this->data['content'] = '<ul class="pageitem"><li class="textbox">'.$message.'</li>'.$url.'</ul>';
    }

    private function getforums($pid="0", $depth=1, $permissions="") {
        global $mybb, $lang, $archiveurl;
        if(is_array($this->fcache[$pid])) {
            foreach($this->fcache[$pid] as $key => $main) {
                foreach($main as $key => $forum) {
                    $perms = $this->forumpermissions[$forum['fid']];
                    if(($perms['canview'] == 1 || $mybb->settings['hideprivateforums'] == 0) && $forum['active'] != 0) {
                        if($forum['linkto']) {
                            $forums .= "<span class=\"graytitle\">".htmlspecialchars($forum['name'])."</span><ul class=\"pageitem\">";
                        }
                        elseif($forum['type'] == "c") {
                            $forums .= "<span class=\"graytitle\">".htmlspecialchars($forum['name'])."</span><ul class=\"pageitem\">";
                        }
                        else {
                            $forums .= "<li class=\"menu\"><a href=\"".$mybb->settings['bburl']."/iphone/index.php/forum-".$forum['fid'].".html\"><span class=\"arrow\" style=\"float: right\"></span><span class=\"name\">".htmlspecialchars($forum['name'])."</span></a>";
                        }
                        if($this->fcache[$forum['fid']] && $depth < 2) {
                            $newdepth = $depth + 1;
                            $forums .= $this->getforums($forum['fid'], $newdepth, $perms);
                            $forums .= "</ul>\n";
                        }
                        $forums .= "</li>\n";
                    }
                }
            }
        }
        return $forums;
    }

    private function getsubforums($pid="0", $name="") {
        global $mybb, $lang, $archiveurl, $db;
        $this->forumpermissions = forum_permissions();

        $query = $db->simple_select("forums", "*", "pid='".$pid."' AND active != '0' AND password=''", array('order_by' => 'pid, disporder'));
        while($forum = $db->fetch_array($query)) {
            $this->fcache[$forum['pid']][$forum['disporder']][$forum['fid']] = $forum;
        }
        $count = 0;
        if(is_array($this->fcache[$pid])) {
            foreach($this->fcache[$pid] as $key => $main) {
                foreach($main as $key => $forum) {
                    $perms = $this->forumpermissions[$forum['fid']];
                    if(($perms['canview'] == 1 || $mybb->settings['hideprivateforums'] == 0) && $forum['active'] != 0) {
                        $dataArray[$count] = "<li class=\"menu\"><a href=\"".$mybb->settings['bburl']."/iphone/index.php/forum-".$forum['fid'].".html\"><span class=\"name\">".htmlspecialchars($forum['name'])."</span><span class=\"arrow\"></span></a>";
                        $count++;
                    }
                }
            }
            if(is_array($dataArray)) {
                $data = "<span class=\"graytitle\">".htmlspecialchars($name)." Subforums</span><ul class=\"pageitem\">";
                $data .= implode("", $dataArray);
                $data .= "</ul>";
                return $data;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }
}
?>
